package com.shuyou;

import com.shuyou.lib.BooksDesListView;
import com.shuyou.lib.BooksDesListViewAdapter;
import com.shuyou.net.BookDetail;
import com.shuyou.net.Data;
import com.shuyou.net.JsonParser;
import com.shuyou.net.ServerInfo;
import com.shuyou.net.StaticHttpClient;
import com.shuyou.utils.AnimationUtil;
import com.shuyou.values.Values;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchResultActivity extends Activity {

    private Handler mHandler;
    private String keyword;
    private RelativeLayout loading;
    
    private ListView list = null;
    private BooksDesListViewAdapter booksDesListAdapter = null;
    private ArrayList<BookDetail> booklist = new ArrayList<BookDetail>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_search_result);
        
        InitListDisplay();
        
        mHandler = new MyHandler(this);
        keyword = this.getIntent().getStringExtra("keyword");
        loading = (RelativeLayout) this.findViewById(R.id.loading_layout);
        new AnimationUtil().showLoadingDialog(loading);
        new SearchThread(keyword).start();
        
        findViewById(R.id.searchresult_back).setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
        });
    }
    
    /*初始化listview的显示*/
    private void InitListDisplay()
    {
    	List<BooksDesListView> booksDesList = new ArrayList<BooksDesListView>();
		for(int i = 0; i < 4; ++ i) {
			BooksDesListView tmpBooksDes = new BooksDesListView("null", "null", "null","null","null");
			booksDesList.add(tmpBooksDes);
		}
		list = (ListView)findViewById(R.id.searchresult_listview);
		booksDesListAdapter = new BooksDesListViewAdapter(SearchResultActivity.this, 
				booksDesList, list);
		list.setAdapter(booksDesListAdapter);
		
		list.setOnItemClickListener(new OnItemClickListener(){
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// TODO Auto-generated method stub
				Intent i = new Intent();
				i.putExtra("bookIsbn", booklist.get(position).getIsbn());
				i.putExtra("bookName", booklist.get(position).getBook_name());
				i.putExtra("bookAuthor", booklist.get(position).getAuthor());
				i.putExtra("bookLabel", booklist.get(position).getLabel());
				i.setClass(SearchResultActivity.this, BookInfoActivity.class);
				startActivity(i);
			}
		});
    }

    @Override
    protected void onDestroy() {
        mHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    class SearchThread extends Thread{

        private String keyword;
        
        public SearchThread(String keyword) {
            this.keyword = keyword;
        }

        @Override
        public void run() {
            String strResult = null;
            Map<String, String> map = new HashMap<String, String>();
            map.put("query", keyword);
            map.put("test", "1");
            try {
                strResult = StaticHttpClient.doGet(
                        Values.SEARCH_URL, map);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ServerInfo si = (ServerInfo) JsonParser.parseObject(strResult,
                    ServerInfo.class);
            System.out.println(si);
            if(si.getStatus().equals("10000"))
            {
                Message msg = new Message();
                msg.obj = si.getData();
                msg.what = Values.SUCCESS_TO_SEARCH;
                mHandler.sendMessage(msg);
            }
        }
        
    }
    
    private void SearchSuccess(Data data)
    {
		if(null == data.getBook_list())
		{
			return ;
		}
    	booksDesListAdapter.clear();
    	int count = 0;
    	for (BookDetail ib : data.getBook_list()) {
			booklist.add(ib);
			/*标签项最多只显示三个*/
			String show_label = null;
			String []labels = ib.getLabel().split(";");
			if(labels.length <= 3) {
				show_label=ib.getLabel();
			} else {
				show_label=labels[0]+";"+labels[1]+";"+labels[2];
			}
			/*书名名最多显示10个字符*/
			String showBookName = null;
			if(ib.getBook_name().length() > 10) {
				showBookName = ib.getBook_name().substring(0, 10) + "..";
			} else {
				showBookName = ib.getBook_name();
			}
			/*人名最多显示10个字符*/
			String showAuthorName = null;
			if(ib.getAuthor().length() > 10) {
				showAuthorName = ib.getAuthor().substring(0, 10) + "..";
			} else {
				showAuthorName = ib.getAuthor();
			}
			
			BooksDesListView booksDes = new BooksDesListView(ib.getBook_link(), showBookName, showAuthorName,
					show_label, ib.getCurrent_available_count());
			booksDesListAdapter.add(booksDes);
			booksDesListAdapter.notifyDataSetChanged();
			++ count;
		}
    	for(int i = count; i < Values.MIN_LINE_DISPLAY; ++i)   //不足四行的，要补气四行
    	{
    		BooksDesListView booksDes = new BooksDesListView("null", "null", "null","null", "null");
			booksDesListAdapter.add(booksDes);
			booksDesListAdapter.notifyDataSetChanged();
    	}
    }
    
    static class MyHandler extends Handler{

        WeakReference<SearchResultActivity> mActivity;
        
        public MyHandler(SearchResultActivity layout) {
        	mActivity = new WeakReference<SearchResultActivity>(layout);
        }

        @Override
        public void handleMessage(Message msg) {
            SearchResultActivity theAct = mActivity.get();
            if(theAct == null)
            {
                return;
            }
            switch (msg.what) {
                case Values.SUCCESS_TO_SEARCH:
                    Data data = (Data)msg.obj;
                    theAct.SearchSuccess(data);
                    break;

                default:
                    break;
            }
            new AnimationUtil().dismissLoadingDialog(theAct.loading);
        }
        
    }
    
}
